好久没写C的,写个C复习一下,写个简单的leetcode吧
- 3Sum Closest
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
这个问题比较简单,我先写了个暴力解法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20int threeSumClosest(int* nums, int numsSize, int target) {
int result=nums[0] + nums[1] + nums[2];
int i, j, k;
int sum;
for(i=0; i<numsSize-2; i++)
{
for(j=i+1; j<numsSize-1; j++)
{
for(k=j+1; k<numsSize; k++)
{
sum = nums[i] + nums[j] + nums[k];
if(abs(sum-target) <= abs(result-target))
result = sum;
}
}
}
return result;
}
runtime为172 ms可想而知是很低的。
看了下别人的solution,先排序再算要快好多,于是我先尝试了
冒泡排序
1 | void bubble_sort(int arr[], int len) { |
Runtime 为8 ms,还是差点,仔细看了下,因该是我的排序算法慢了,看到别人的solution用c中的快排qsort()
,可惜我之前没学过这个函数,所以没想到,赶紧恶补下。
1 | void qsort( |
使用快排后
Runtime: 4 ms, faster than 100.00% of C online submissions for 3Sum Closest.
1 | int comp(const void*a,const void*b) |